import { db, _c } from "..";
import { SUCCESS_CODE, ERROR_CODE } from "@/service";

export interface PayloadDTO {
    type?:string;
    elements?: any[];
    diagramId?: string | undefined;
  }

  export const addPayload = (payload:PayloadDTO) => {
    return db
      .collection("payloads")
      .add(payload)
      .then((res) => {
        if (res) {
          return {
            code: SUCCESS_CODE,
            data: true,
            message: "",
          };
        } else {
          return {
            code: ERROR_CODE,
            data: false,
            message: "信息更新错误",
          };
        }
      })
      .catch((err) => ({
        code: ERROR_CODE,
        data: false,
        message: "信息更新错误",
      }));
  };

  export const removePayload = (id:string) => {
    return db
      .collection("payloads")
      .where(
        {
          diagramId:id,
        }
      )
      .remove()
      .then((res) => {
        if (res) {
          return {
            code: SUCCESS_CODE,
            data: true,
            message: "",
          };
        } else {
          return {
            code: ERROR_CODE,
            data: false,
            message: "信息更新错误",
          };
        }
      })
      ;
  };

export const updatePayload = (payload: PayloadDTO) => {
    return db
      .collection("payloads")
      .where(
        {diagramId:payload.diagramId
        }
        )
      .update(
        {
         elements:payload.elements,
         type:payload.type,
        }
      )
      .then((res) =>{
        if (res) {
          return {
            code: SUCCESS_CODE,
            data: true,
            message: "",
          };
        } else {
          return {
            code: ERROR_CODE,
            data: false,
            message: "信息更新错误",
          };
        }
      });
  };

  export const getPayloadInfo = (UUID: string) => {
    return db
      .collection("payloads")
      .where({ UUID: _c.eq(UUID) })
      .get()
      .then(({ data }) => {
        if (data.length < 1) {
          return false;
        } else {
          return data;
        }
      });
  };
  